
package com.zhuoyue.system.service.impl;

import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.zhuoyue.common.core.domain.ServiceResult;
import com.zhuoyue.common.core.domain.entity.SysThirdData;
import com.zhuoyue.common.exception.ServiceException;
import com.zhuoyue.system.mapper.TblMessageMapper;
import com.zhuoyue.system.service.JPushService;
import com.zhuoyue.system.util.api.XmlParse;
import com.zhuoyue.system.util.xml.XmlParseByTypeAndCode;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;


/**
 * ClassName: JPushServiceImpl <br/>
 * Description: <br/>
 * date: 2019/2/19 18:02<br/>
 *
 * @author wjming<br />
 * @version 1.0
 */

@Service("jPushService")
public class JPushServiceImpl implements JPushService {
    private static JPushClient jPushClient = new JPushClient(MASTER_SECRET, APP_KEY);
    @Autowired
    //private MessageDao messageDao;
    private TblMessageMapper messageDao;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServiceResult sendAll(String title, String message, String messageType, String extrasType, String extrasContent, String organization)
            throws Exception {
        //xml文件解析
        XmlParseByTypeAndCode xmlParseByTypeAndCode = new XmlParseByTypeAndCode();
        XmlParse xmlParse = xmlParseByTypeAndCode.getKeyAndSecret("jpush", organization, null);
        JPushClient jPushClient = new JPushClient(xmlParse.getSecret(), xmlParse.getKey());

        Map<String, String> extrasMap = new HashMap<String, String>();
        extrasMap.put("type", extrasType);
        extrasMap.put("content", extrasContent);

        PushPayload payload = buildPushObject_all_alias_alert(title, message, extrasMap, Audience.all(), xmlParse.getUriActivity(), xmlParse.getUriAction());
        PushResult result = jPushClient.sendPush(payload);
        //System.out.println(result.isResultOK() + "-" + result.getResponseCode() + "-" + result.getOriginalContent());
       /* if (!result.isResultOK()){
            throw new ServiceException(String.valueOf(result.getResponseCode()), result.getOriginalContent());
        }*/


        URIBuilder uriBuilder = new URIBuilder("http://121.196.208.131:8081/api/message/manageAdd");
        //URIBuilder uriBuilder = new URIBuilder("http://localhost:8081/api/message/manageAdd");
        uriBuilder.addParameter("sender", "ALL");
        uriBuilder.addParameter("sendType", "2");
        uriBuilder.addParameter("messageType", messageType);
        uriBuilder.addParameter("content", message);
        uriBuilder.addParameter("userId", organization);
        uriBuilder.addParameter("title", title);


        // 根据带参数的URI对象构建GET请求对象
        HttpPost httpPost = new HttpPost(uriBuilder.build());
        CloseableHttpResponse response = null;
        // 获取连接客户端工具
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 执行请求
        response = httpClient.execute(httpPost);
        return new ServiceResult();
    }

    @Override
//    @Transactional(rollbackFor = Exception.class)
    public ServiceResult send(String title, String message, String messageType, String registrationId,
                              String extrasType, String extrasContent, String userId, String sourceType, SysThirdData sysThirdData) throws Exception {
        JPushClient jPushClient = new JPushClient(sysThirdData.getSecret(), sysThirdData.getDataKey());


        URIBuilder uriBuilder = new URIBuilder("http://121.196.208.131:8081/api/message/manageAdd");
        uriBuilder.addParameter("sender", registrationId);
        uriBuilder.addParameter("hasRead", "0");
        uriBuilder.addParameter("sendType", sourceType);
        uriBuilder.addParameter("messageType", messageType);
        uriBuilder.addParameter("content", message);
        uriBuilder.addParameter("userId", userId);
        uriBuilder.addParameter("title", title);


        // 根据带参数的URI对象构建GET请求对象
        HttpPost httpPost = new HttpPost(uriBuilder.build());
        CloseableHttpResponse response = null;
        // 获取连接客户端工具
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 执行请求
        response = httpClient.execute(httpPost);


        //推送
        Map<String, String> extrasMap = new HashMap<String, String>();

        PushPayload payload = null;

//		PushPayload payload = buildPushObject_all_alias_alert(title, message, extrasMap,
//				Audience.registrationId(registrationId));

        //安卓正常推送，苹果静默推送
        PushResult result = null;
        extrasMap.put("type", extrasType);
        extrasMap.put("content", extrasContent);
        extrasMap.put("ios", message);
        payload = buildPushObject_all_alias_alert(title, message, extrasMap, Audience.registrationId(registrationId), sysThirdData.getUriActivity(), sysThirdData.getUriAction());
        result = jPushClient.sendPush(payload);
        System.out.println(result.isResultOK() + "-" + result.getResponseCode() + "-" + result.getOriginalContent());


        //苹果正常推送
        if (sourceType.equals("1")) {
            //由于服务器发送速度比较快，极光推送发过去以后苹果会收不到两条消息，所以需要延迟500毫秒
            Thread.sleep(500);
            extrasMap.put("type", extrasType);
            extrasMap.put("content", null);
            payload = buildPushObject_ios_tagAnd_alertWithExtrasAndMessage(title, message, extrasMap, Audience.registrationId(registrationId));
            result = jPushClient.sendPush(payload);
            System.out.println(result.isResultOK() + "-" + result.getResponseCode() + "-" + result.getOriginalContent());
        }


        if (!result.isResultOK()) {
            throw new ServiceException(String.valueOf(result.getResponseCode()), result.getOriginalContent());
        }


//		PushResult result = jPushClient.sendPush(payload);
//		System.out.println(result.isResultOK() + "-" + result.getResponseCode() + "-" + result.getOriginalContent());
//		if (!result.isResultOK())
//			throw new ServiceException(String.valueOf(result.getResponseCode()), result.getOriginalContent());

        return new ServiceResult();
    }

    /**
     * 构建推送对象
     * 安卓的正常推送IOS静默推送
     *
     * @param title
     * @param message
     * @param extras
     * @param audience
     * @return
     * @throws Exception
     */
    public PushPayload buildPushObject_all_alias_alert(String title, String message, Map<String, String> extras, Audience audience, String uri_activity, String uri_action) throws Exception {
        // 指定要推送的平台，all代表当前应用配置了的所有平台，也可以传android等具体平台
        // 指定推送的接收对象，all代表所有人，也可以指定已经设置成功的tag或alias或应用客户端调用接口获取到的registrationID
        return PushPayload.newBuilder().setPlatform(Platform.all())
                .setAudience(audience)
                // 发送通知
                .setNotification(Notification.newBuilder()
                        // Android
                        .addPlatformNotification(AndroidNotification.newBuilder().setAlert(message).setTitle(title)
                                .addExtras(extras).addExtra("uri_activity", uri_activity).addCustom("uri_activity", uri_activity).addCustom("uri_action", uri_action)
                                .addExtra("uri_action", uri_action).build())

                        // Ios
                        .addPlatformNotification(IosNotification.newBuilder().setAlert("").setBadge(0)
                                .addExtras(extras).setContentAvailable(true).build())
                        .build())
                // 发送消息
                .setMessage(Message.newBuilder().setMsgContent(message).addExtras(extras).build())
                // 设置ios平台Apns环境 True 表示推送生产环境，False 表示要推送开发环境 默认是开发
                .setOptions(Options.newBuilder().setApnsProduction(true).setTimeToLive(864000).build()).build();
    }


    //ios第一条的推送
    public static PushPayload buildPushObject_ios_tagAnd_alertWithExtrasAndMessage(String title, String message, Map<String, String> extras, Audience audience) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.ios())
                .setAudience(audience)
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(message)
                                .setSound("default")
                                .addExtras(extras).setBadge(0)
//								.setContentAvailable(false)
                                .build())
                        .build())
                .setMessage(Message.newBuilder().setMsgContent(message).addExtras(extras).build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(true)
                        .build())
                .build();
    }


    @Override
//    @Async("taskExecutor")
    public ServiceResult sendAndroid(SysThirdData sysThirdData, String extrasType, String userId, String title, String content, String messageType, String sourceId) throws Exception {
        // 发送日志推送
        addPushLog(userId, title, content, sourceId, "2", messageType);

        //推送
        firstSend(sysThirdData, extrasType, title, content, sourceId);
        return null;
    }

    @Override
//    @Async("taskExecutor")
    public ServiceResult sendIos(SysThirdData sysThirdData, String extrasType, String userId, String title, String content, String messageType, String sourceId) throws Exception {
        // 发送日志推送
        addPushLog(userId, title, content, sourceId, "1", messageType);
        // 第一次
        firstSend(sysThirdData, extrasType, title, content, sourceId);

        // 再次推送
        Thread.sleep(500);
        Map<String, String> extrasMap = new HashMap<>(2);
        extrasMap.put("type", extrasType);
        extrasMap.put("content", null);
        extrasMap.put("ios", content);
        PushPayload payload = buildPushObject_ios_tagAnd_alertWithExtrasAndMessage(title, content, extrasMap, Audience.registrationId(sourceId));
        JPushClient jPushClient = new JPushClient(sysThirdData.getSecret(), sysThirdData.getDataKey());
        jPushClient.sendPush(payload);
        return null;
    }

    /**
     * 第一次推送
     *
     * @param sysThirdData
     * @param extrasType
     * @param title
     * @param content
     * @param sourceId
     * @throws Exception
     */
    private void firstSend(SysThirdData sysThirdData, String extrasType, String title, String content, String sourceId) throws Exception {
        //推送
        Map<String, String> extrasMap = new HashMap<>(3);
        extrasMap.put("type", extrasType);
        extrasMap.put("content", "");
        extrasMap.put("ios", content);
        JPushClient jPushClient = new JPushClient(sysThirdData.getSecret(), sysThirdData.getDataKey());
        PushPayload payload = buildPushObject_all_alias_alert(title, content, extrasMap, Audience.registrationId(sourceId), sysThirdData.getUriActivity(), sysThirdData.getUriAction());
        jPushClient.sendPush(payload);
    }

    /**
     * 推送日志添加
     *
     * @param userId
     * @param title
     * @param content
     * @param sourceId
     * @param sourceType  手机系统类型 1-苹果手机 2-安卓手机
     * @param messageType 固定"8"
     * @throws Exception
     */
    private void addPushLog(String userId, String title, String content, String sourceId, String sourceType, String messageType) throws Exception {
        URIBuilder uriBuilder = new URIBuilder("http://121.196.208.131:8081/api/message/manageAdd");
        uriBuilder.addParameter("userId", userId);
        uriBuilder.addParameter("hasRead", "0");
        uriBuilder.addParameter("content", content);
        uriBuilder.addParameter("title", title);
        uriBuilder.addParameter("sender", sourceId);
        uriBuilder.addParameter("sendType", sourceType);
        uriBuilder.addParameter("messageType", messageType);


        // 根据带参数的URI对象构建GET请求对象
        HttpPost httpPost = new HttpPost(uriBuilder.build());
        CloseableHttpResponse response = null;
        // 获取连接客户端工具
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 执行请求
        httpClient.execute(httpPost);
    }
}

